package com.ly.consumer.listeners;

import com.ly.consumer.common.constants.MqConstants;
import com.ly.consumer.common.mq.DelayMessagrProcessor;
import com.ly.consumer.common.utils.MultiDelayMessage;
import com.ly.consumer.server.IOrderServer;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 23087
 */
@Component
@RequiredArgsConstructor
public class OrderStatusCheckListener {

    private final IOrderServer orderServer;

    private final RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.DELAY_ORDER_QUEUE,durable = "true"),
            exchange = @Exchange(value = MqConstants.DELAY_EXCHANGE,delayed = "true",type = ExchangeTypes.TOPIC),
            key = MqConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenOrderDelayMessage(MultiDelayMessage<Long> msg) {
        // 1. 查询订单状态

        // 2.判断是否已支付

        // todo 3. 去支付服务查询真正的之支付状态
        boolean isPay = false;
        // 3.1 已支付，标记订单状态为已支付 (直接返回)
        if (isPay){
            // todo 标记未支付订单为已支付
            return;
        }
        // 3.2 未支付，获取下次订单延迟时间

        // 4. 判断是否存在延迟时间
        if(msg.hashNetDelay()){
            // 4.1 存在，重发延迟消息
            Long nextDelay = msg.removeNextDelay();
            rabbitTemplate.convertAndSend(MqConstants.DELAY_EXCHANGE,MqConstants.DELAY_ORDER_ROUTING_KEY,msg,
                    new DelayMessagrProcessor(nextDelay.intValue()));
            return;
        }
        // todo 5、 不存在，调用订单服务，取消订单-恢复库存
        orderServer.cancelOrder(msg.getData());




    }

}
